<?php

/**
 * 用户角色模型
 */
class User_role_model extends CI_Model {
    
    const TN = "user_roles";
    
    public function insert($user_role) {
        $this->db->insert(self::TN, $user_role);
    }
    
    /**
     * 按用户删除
     * @param type $uid
     */
    public function delete_batch_by_user($uid) {
        $this->db->delete(self::TN, array('ur_uid' => $uid));
    }
    
    /**
     * 取得拥有某角色的用户id数组
     * @return array()
     */
    public function get_role_uids($rid) {
        $result = array();

        $rows = $this->fetch_array(array('rid' => $rid, 'active' => true));
        foreach ($rows as $row) {
            $result[] = $row['ur_uid'];
        }
        
        return $result;
    }
    
    /**
     * 取得某用户拥有的角色数组
     * @param type $uid
     */
    public function get_user_rids($uid) {
        $result = array();

        $rows = $this->fetch_array(array('uid' => $uid, 'active' => true));
        foreach ($rows as $row) {
            $result[] = $row['ur_rid'];
        }
        
        return $result;
    }

        /**
     * 
     * @param type $conditions
     * @param type $per_page 默认0表示取所有记录
     * @param type $page
     * @return array
     */
    public function fetch_array($conditions, $per_page = 0, $page = 0) {
        $this->_set_where($conditions);
        if ($per_page > 0) {
            $offset = ($page - 1) * $per_page;
            $this->db->limit($per_page, $offset);
        }

        return $this->db->get(self::TN)->result_array();
    }
    
    /**
     * 设置where
     * @param type $conditions
     */
    private function _set_where($conditions) {
        /* 用户 */
        if (isset($conditions['uid'])) {
            $this->db->where('ur_uid', $conditions['uid']);
        }
        
        /* 角色 */
        if (isset($conditions['rid'])) {
            $this->db->where('ur_rid', $conditions['rid']);
        }
        
        /* 有效的 */
        if (isset($conditions['active'])) {
            $today = date('Y-m-d');
            $this->db->where('ur_first_date <=', $today);
            $this->db->where('ur_last_date >=', $today);
        }
    }
}

